﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SP = Microsoft.SharePoint.Client;
using System.IO;

namespace com.sharepointutils.application.Forms
{
    public partial class TransferForm : Form
    {
        public SiteInformation ToConnection { get; set; }
        String ToList { get; set; }
        public SiteInformation FromConnection { get; set; }
        String FromList { get; set; }

        public TransferForm(SiteInformation toConnection, String toList, String toLabel, SiteInformation fromConnection, String fromList, String fromLabel)
        {
            InitializeComponent();

            ToConnection = toConnection;
            ToList = toList;
            this.FromConnection = fromConnection;
            FromList = FromList;
            lbl_transfer_from.Text = fromLabel;
            lbl_transfer_to.Text = toLabel;
        }

        private void btn_transfer_Click(object sender, EventArgs e)
        {

        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            SP.ListItemCollection collection = SharePointUtilities.getAllListItems(FromConnection.URL, FromList, FromConnection.Credentials);
            double count = 0;
            double total = collection.Count;

            foreach (SP.ListItem x in collection)
            {
                String path = Path.GetFileName(x["FileRef"].ToString());
                try
                {
                    String column = (x["Documentation_x0020_Type"] != null) ? x["Documentation_x0020_Type"].ToString() : "";
                    String html = x["WikiField"].ToString();
                    html = html.Replace("Edge%20Images", @"edgedoc/Images1");
                    html = html.Replace(@"/Lists/Business%20Definition%20Guide/", @"/edgedoc/Lists/Edge%20Business%20Definition%20Guide/");
                    html = html.Replace(@"/Edge/", @"/edgedoc/SitePages/");
                    SharePointUtilities.uploadWikiPage(ToConnection.URL, ToConnection.Credentials, ToList, path, html, column);
                }
                catch
                {
                    //errorLog.Append("Failed to transfer " + path);
                }
                count++;
                backgroundWorker.ReportProgress((int)((count / total) * 100));
            }
        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progbar_status.Value = e.ProgressPercentage;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //txt_errorLog.Text = errorLog.ToString();
            lbl_status.Text = "Done...";
            progbar_status.Value = 100;
        }
    }
}
